package cc.linker.steplink.crm.controller.h5;

import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.utils.AesEncryptUtils;
import cc.linker.steplink.crm.commons.utils.StringUtil;
import cc.linker.steplink.crm.commons.yzj.YzjRequest;
import cc.linker.steplink.crm.dao.CustomerDao;
import cc.linker.steplink.crm.dao.PreciseDao;
import cc.linker.steplink.crm.merchant.service.WxService;
import cc.linker.steplink.crm.commons.utils.MD5;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import cc.linker.steplink.crm.merchanth5.service.VipCustomerLogService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.service.ISyncService;
import cc.linker.steplink.crm.service.PersonalService;
import com.alibaba.fastjson.JSON;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * h5登录跳转
 * 从公众号菜单入口或前端自定义调用，包装后跳转微信矩阵授权
 */
@Slf4j
@Controller
public class H5LoginController {
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private PersonalService personalService;
    @Autowired
    private MallService mallService;
    @Autowired
    private WxService wxService;
    @Autowired
    private PreciseDao preciseDao;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private VipCustomerLogService vipCustomerLogService;
    @Autowired
    private YzjRequest yzjRequest;
    @Autowired
    private ISyncService syncService;


    @Value("${system.visitorToken}")
    private String visitorToken;
    @Value("${spring.profiles.active}")
    private String profile;

    /**
     * 请求微信矩阵获取openid地址
     */
    private final static String H5_LOGIN_URL = "index.php?s=/Home/WxService/getOpenidStep";
    private final static String H5_SH5 = "SH5:";
    public final static String H5_SH5CHECK = "SH5CHECK:";

    /**
     * 根据openId登录(原来是customerId，不改前端)
     */
    @RequestMapping("/personal/loginByCid")
    public String loginByCid(String cid,Integer isWx,String m) {
        LOGGER.info("登录参数： cid="+cid+"  isWx="+isWx  +"  m = "+m);
        Map<String, Object> customer = personalService.getCustomerByOpenId(cid);
        if(customer==null){
            throw GlobalException.build("无此用户");
        }
        String orgId = customer.get("orgId").toString();
        String globalopenId = cid;
        String token = "";
        String openId = cid;
        String customerId = "";
        if(!StringUtils.isEmpty(customer.get("token"))){
            token = customer.get("token").toString();
        }
        if(!StringUtils.isEmpty(customer.get("customerId"))){
            customerId = customer.get("customerId").toString();
        }
        Integer payMode = mallService.getPayModeByOrgId(orgId);
        String key = MD5.encode(orgId + globalopenId);
        String h5User = stringRedisTemplate.opsForValue().get("login:" + key);

        //region 进行用户在我们系统中的注册，redis存储
        WxUser wxUser = null;

        if (StringUtils.isEmpty(h5User)) {
            wxUser = personalService.getAllUser(globalopenId, token, openId,orgId,customerId);
            if (wxUser != null) {
                wxUser.setPayOpenId(wxUser.getOpenid());
            }
        } else {
            wxUser = JSON.parseObject(h5User, WxUser.class);
        }
        if (wxUser == null) {
            LOGGER.info("h5登录失败-----wxUser == null，");
            throw GlobalException.build("h5登录失败");
        }
        //endregion
        Integer isVip = vipCustomerLogService.getIsVip(wxUser.getCustomerId(), wxUser.getOrgId());
        wxUser.setIsVip(isVip);
        h5User = JSON.toJSONString(wxUser);
        stringRedisTemplate.opsForValue().set("login:" + key, h5User, 15, TimeUnit.MINUTES);
        //如果是联汇支付模式;
        if (isWx!=null && isWx==1 && payMode == 3) {
            //region 如果支付模式是联汇支付模式，那么需要再次进行公众号登录，登录主体为 联汇
            try {
                if ("dev".equals(profile)) {
                    return "redirect:" + this.getRedirectH5Url(wxUser, m, token,cid);
                }
                String linkerToken = preciseDao.getTokenByOrgId("linker");
                String oldToken = token;
                if (linkerToken != null && linkerToken.equals(token)) {
                    oldToken = "linker";
                }
                String calback = systemProperties.getScrmUrl() + Constants.URI_H5_LOGIN_CALLBACK + "?originalToken=" + oldToken
                        + "&originalOpenId=" + globalopenId + "&m=" + URLEncoder.encode(m, "UTF-8");


                return "redirect:" + systemProperties.getWxMatrix() + H5_LOGIN_URL + "&token=" + linkerToken + "&callback="
                        + URLEncoder.encode(calback, "UTF-8");
            } catch (Exception ex) {
                LOGGER.warn("H5登录失败---payMode=3，第一次登录报错:" + ex);
                ex.printStackTrace();
                throw GlobalException.build("H5登录失败");
            }
            //endregion
        } else {
            //region 不是联汇支付模式则直接重定向到H5前端
            return "redirect:" + this.getRedirectH5Url(wxUser, m, token,cid);
            //endregion
        }

    }


    /**
     * 根据customerId登录
     */
    @RequestMapping("/personal/loginByCustomerId")
    @ResponseBody
    public String loginByCustomerId(String customerId, HttpServletRequest request) {
        String openId = customerId;
        if (stringRedisTemplate.opsForValue().size("login:" + customerId) > 0) {
            stringRedisTemplate.expire("login:" + customerId, 15, TimeUnit.MINUTES);
            return customerId;
        } else {
            Map<String, Object> customer = personalService.getCustomerByCustomerId(customerId);
            customerId = (String) customer.get("customerId");
            String orgId = (String) customer.get("orgId");
            if (StringUtils.isEmpty(customerId) || StringUtils.isEmpty(orgId)) {
                throw GlobalException.build("用户信息不完整");
            }
//            String openId = (String) customer.get("openId");
            String token = (String) customer.get("token");
            String payOpenId = (String) customer.get("payOpenId");
            String customerName = (String) customer.get("customerName");
            Integer payMode = mallService.getPayModeByOrgId(orgId);
            WxUser wxUser = new WxUser(openId, payOpenId, token, customerName, orgId, customerId,
                    openId, payMode, 0, "",
                    (customer.containsKey("cover") && !StringUtils.isEmpty(customer.get("cover")) ? customer.get("cover").toString() : ""), "");

            stringRedisTemplate.opsForValue().set("login:" + customerId, JSON.toJSONString(wxUser), 15, TimeUnit.MINUTES);
            return customerId;
        }
    }


    /**
     * 获取openid，微信appCode和公号token任选其一
     *
     * @param session
     * @param appCode 微信appCode
     * @param token   公号token
     * @param m       登录模块 uc 用户中心 mall 商城
     * @return 重定向到微信矩阵
     * @throws GlobalException
     */
    @RequestMapping("/" + Constants.URI_H5_LOGIN)
    public String login(String appCode, String token, @RequestParam(defaultValue = "uc") String m, String yzjMemberCode, HttpServletRequest request, String appUserId, String appId, String expandInfo, HttpServletResponse response)
            throws GlobalException, UnsupportedEncodingException {
        //TODO 雅智捷对接
        LOGGER.info("login---------memberCode:" + yzjMemberCode + "---------callback:" + m + "-----------token:" + token);
        if (!StringUtils.isEmpty(yzjMemberCode)) {
            return this.yzjLogin(yzjMemberCode, m, token);
        } else if (!StringUtils.isEmpty(expandInfo) && !StringUtils.isEmpty(appId)) {
            //第三方APP登陆
            return appLoginThrid(expandInfo, appId, m, request, response);
        } else if (!StringUtils.isEmpty(appUserId) || !StringUtils.isEmpty(appId)) {
            //APP登陆
            return appLogin(appUserId, appId, m, request, response);
        } else {
            if (!StringUtils.isEmpty(token) && token.contains("?")) {
                token = token.substring(0, token.indexOf("?"));
            }
            String tokenKeyValue;
            String wxToken = token;
            if (!StringUtils.isEmpty(appCode)) {
                wxToken = wxService.getTokenByAppId(appCode);
                tokenKeyValue = "&wx_appid=" + appCode;
            } else if (!StringUtils.isEmpty(token)) {
                tokenKeyValue = "&token=" + token;
            } else {
                throw GlobalException.build("非法参数");
            }
            String calback = systemProperties.getScrmUrl() + Constants.URI_H5_LOGIN_CALLBACK + "?originalToken=" + wxToken + "&m="
                    + URLEncoder.encode(m, "UTF-8");
            if (StringUtils.isEmpty(systemProperties.getWxMatrix())) {
                LOGGER.info("矩阵地址为空");
            }
            if ("dev".equals(profile)) {
                return "redirect:" + systemProperties.getScrmUrl() + Constants.URI_H5_LOGIN_CALLBACK +
                        "?originalToken=gh_6ea99e214a63&globalopenId=ogqK9wDJYusIzBHPXkFd2miEFXKk&openId=ogqK9wDJYusIzBHPXkFd2miEFXKk&token=gh_6ea99e214a63&m=" + URLEncoder.encode(m, "UTF-8");
            } else {
                return "redirect:" + systemProperties.getWxMatrix() + H5_LOGIN_URL + tokenKeyValue + "&callback="
                        + URLEncoder.encode(calback, "UTF-8");
            }
        }
    }


    /**
     * 微信矩阵回调
     *
     * @param m            h5模块地址
     * @param token
     * @param openId
     * @param globalopenId
     * @return 重定向到h5地址
     * @throws GlobalException
     */
    @RequestMapping("/" + Constants.URI_H5_LOGIN_CALLBACK)
    public String callbackLogin(String globalopenId, String token, String originalToken, String openId, String originalOpenId, String m)
            throws GlobalException {
        if (token.equals(originalToken)) {
            String orgId = personalService.getOrgByToken(token);
            Integer payMode = mallService.getPayModeByOrgId(orgId);
            String key = MD5.encode(orgId + globalopenId);
            String h5User = stringRedisTemplate.opsForValue().get("login:" + key);

            //region 进行用户在我们系统中的注册，redis存储
            WxUser wxUser = null;

            if (StringUtils.isEmpty(h5User)) {
                wxUser = personalService.saveWxH5User(globalopenId, token, openId);
                if (wxUser != null) {
                    wxUser.setPayOpenId(wxUser.getOpenid());
                }
            } else {
                wxUser = JSON.parseObject(h5User, WxUser.class);
            }
            if (wxUser == null) {
                LOGGER.info("h5登录失败-----wxUser == null，");
                throw GlobalException.build("h5登录失败");
            }
            //endregion
            Integer isVip = vipCustomerLogService.getIsVip(wxUser.getCustomerId(), wxUser.getOrgId());
            wxUser.setIsVip(isVip);
            h5User = JSON.toJSONString(wxUser);
            stringRedisTemplate.opsForValue().set("login:" + key, h5User, 15, TimeUnit.MINUTES);
            //如果是联汇支付模式;
            if (payMode == 3) {
                //region 如果支付模式是联汇支付模式，那么需要再次进行公众号登录，登录主体为 联汇
                try {
                    if ("dev".equals(profile)) {
                        return "redirect:" + this.getRedirectH5Url(wxUser, m, token,null);
                    }
                    String linkerToken = preciseDao.getTokenByOrgId("linker");
                    String oldToken = token;
                    if (linkerToken != null && linkerToken.equals(token)) {
                        oldToken = "linker";
                    }
                    String calback = systemProperties.getScrmUrl() + Constants.URI_H5_LOGIN_CALLBACK + "?originalToken=" + oldToken
                            + "&originalOpenId=" + globalopenId + "&m=" + URLEncoder.encode(m, "UTF-8");


                    return "redirect:" + systemProperties.getWxMatrix() + H5_LOGIN_URL + "&token=" + linkerToken + "&callback="
                            + URLEncoder.encode(calback, "UTF-8");
                } catch (Exception ex) {
                    LOGGER.warn("H5登录失败---payMode=3，第一次登录报错:" + ex);
                    ex.printStackTrace();
                    throw GlobalException.build("H5登录失败");
                }
                //endregion
            } else {
                //region 不是联汇支付模式则直接重定向到H5前端
                return "redirect:" + this.getRedirectH5Url(wxUser, m, token,null);
                //endregion
            }
        } else {
            //region 只有当联汇支付模式，第二次以联汇公众号授权登录的才会当前token 不等于 originalToken  ，代表二次登录需要走这个逻辑
            // 1、需要修改当前登录用户对应的payOpenId到数据库
            // 2、需要修改redis当前登录用户的信息
            // 3、写入session并跳转到前端
            if (originalToken.equals("linker")) {
                originalToken = token;
            }
            String orgId = personalService.getOrgByToken(originalToken);
            String key = MD5.encode(orgId + originalOpenId);
            String h5User = stringRedisTemplate.opsForValue().get("login:" + key);
            if (!StringUtils.isEmpty(h5User)) {
                WxUser wxUser = JSON.parseObject(h5User, WxUser.class);
                personalService.updatePayOpenIdByCustomerId(wxUser.getCustomerId(), globalopenId);
                wxUser.setPayOpenId(globalopenId);
                wxUser.setToken(token);
                stringRedisTemplate.opsForValue().set("login:" + key, JSON.toJSONString(wxUser), 15, TimeUnit.MINUTES);
                //重定向到H5前端
                return "redirect:" + this.getRedirectH5Url(wxUser, m, originalToken,null);
            } else {
                LOGGER.info("H5登录失败---token为联汇的时候报错了");
                throw GlobalException.build("h5登录失败");
            }
            //endregion
        }
    }



   /**
     * 蓝色星球登录
     *
     * @param m           h5模块地址
     * @param wxappid
     * @param openId
     * @ url : route/login
     * @return 重定向到h5地址
     * @throws GlobalException
     */
    @RequestMapping("/" + Constants.URI_ROUTE_LOGIN_CALLBACK)
    public String  routeLogin(String openId, String wxappid, String orgId,String m)throws GlobalException {
             LOGGER.info("蓝色星球登录参数-----openId="+openId+"  wxappid="+wxappid+"  orgId="+orgId);
            String key = MD5.encode(orgId + openId);
            WxUser wxUser = personalService.saveRouteUser(openId, wxappid,orgId);
            if (wxUser != null) {
                wxUser.setPayOpenId(wxUser.getOpenid());
            }

            if (wxUser == null) {
                LOGGER.info("h5登录失败-----wxUser == null，");
                throw GlobalException.build("h5登录失败");
            }
            //endregion
            Integer isVip = vipCustomerLogService.getIsVip(wxUser.getCustomerId(), wxUser.getOrgId());
            wxUser.setIsVip(isVip);
            String h5User = JSON.toJSONString(wxUser);
            stringRedisTemplate.opsForValue().set("login:" + key, h5User, 15, TimeUnit.MINUTES);
        return "redirect:" + this.getRedirectH5Url(wxUser, m, wxappid,openId);
    }

    //跳转到前端
    private String getRedirectH5Url(WxUser wxUser, String m, String token,String openId) {
        String moduleUrl;
        String key = MD5.encode(wxUser.getOrgId() + wxUser.getGlobalOpenid());
        String h5TokenParam = "?t=" + System.currentTimeMillis() + "&tk=" + token + "&ht=" + key;
        if(!StringUtils.isEmpty(openId)){
            h5TokenParam =h5TokenParam +"&cid="+openId;
        }
        String scrmWebUrl = systemProperties.getAcsScrmWebUrl();
        if (WebModule.USER_CENTER.getModule().equals(m)) {
            moduleUrl = scrmWebUrl + Constants.URI_H5_USER_CENTER + h5TokenParam;
        } else if (WebModule.MALL.getModule().equals(m)) {
            moduleUrl = scrmWebUrl + Constants.URI_H5_MALL + h5TokenParam;
        } else {
            if (m.indexOf(".html") > -1) {
                moduleUrl = m.replaceFirst("\\.html\\??", ".html" + h5TokenParam + "&");
            } else if (m.indexOf("?") > -1) {
                h5TokenParam = "&t=" + System.currentTimeMillis() + "&tk=" + token + "&ht=" + key;
                moduleUrl = m + h5TokenParam;
            } else {
                moduleUrl = m + h5TokenParam;
            }
        }
        return moduleUrl;
    }

    @ResponseBody
    @PostMapping("/applets/login")
    public Map<String, Object> appletsLogin(@RequestBody Map<String, Object> params) {
        Map<String, Object> resultMap = new HashMap<>();
        String openid = (String) params.get("openid");
        if (StringUtils.isEmpty(openid)) {
            throw GlobalException.build("缺少参数");
        }
        Map<String, Object> customer = personalService.getMissCustomerByOpenId(openid);
        if (customer == null) {
            throw GlobalException.build("用户不存在");
        }
        String customerId = (String) customer.get("customerId");
        String orgId = (String) customer.get("orgId");
        String bindPhone = customer.containsKey("bindPhone") && customer.get("bindPhone") != null ? customer.get("bindPhone").toString() : "";
        if (StringUtils.isEmpty(customerId) || StringUtils.isEmpty(orgId)) {
            throw GlobalException.build("用户信息不完整");
        }

        String key = MD5.encode(orgId + openid);
        String s = stringRedisTemplate.opsForValue().get("login:" + key);

        if (!StringUtils.isEmpty(s)) {
            stringRedisTemplate.expire("login:" + key, 15, TimeUnit.MINUTES);
            resultMap.put("HT", key);
            return resultMap;
        }
        Integer payMode = mallService.getPayModeByOrgId(orgId);
        WxUser wxUser = new WxUser(openid, null, "", "nickname", orgId,
                customerId, openid, payMode, 0, bindPhone,
                (customer.containsKey("cover") && !StringUtils.isEmpty(customer.get("cover")) ? customer.get("cover").toString() : ""), "");
        stringRedisTemplate.opsForValue().set("login:" + key, JSON.toJSONString(wxUser), 15, TimeUnit.MINUTES);
        resultMap.put("HT", key);
        return resultMap;
    }

    @GetMapping("/app/login")
    public String appLoginE(String appUserId, String appId, @RequestParam(defaultValue = "uc") String m, HttpServletRequest request, HttpServletResponse response) throws GlobalException, UnsupportedEncodingException {
        return login(null, null, m, null, request, appUserId, appId, null, response);
    }

    //@GetMapping("/app/login")
    public String appLogin(String appUserId, String appId, @RequestParam(defaultValue = "uc") String m, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(appUserId) || StringUtils.isEmpty(appId)) {
            throw GlobalException.build("缺少参数");
        }
        String oldAppUserId;
        try {
            appUserId = appUserId.replaceAll(" ", "+");
            oldAppUserId = appUserId;
            appUserId = AesEncryptUtils.decrypt(appUserId);
        } catch (Exception e) {
            e.printStackTrace();
            throw GlobalException.build("参数错误");
        }
        Map<String, Object> customer = personalService.getAppCustomerByAppUserId(appUserId, appId);
        Integer isVip = 0;
        Integer newIsVip = 0;
        String bindPhone = "";
        if (customer == null) {
            // 没有用户，调接口同步用户
            customer = personalService.getAppCustomer(appUserId, appId);
        } else {
            // 已有用户，直接登录，调接口更新用户
            newIsVip = personalService.updateAppCustomer(appUserId, appId);
            bindPhone = customer.containsKey("bindPhone") && customer.get("bindPhone") != null ? customer.get("bindPhone").toString() : "";
            personalService.updateAppCustomer(appUserId, appId);
        }
        //获取用户是否是vip
        isVip = vipCustomerLogService.getIsVip(customer.get("customerId").toString(), customer.get("orgId").toString());

        String customerId = (String) customer.get("customerId");
        String orgId = (String) customer.get("orgId");
        if (StringUtils.isEmpty(customerId) || StringUtils.isEmpty(orgId)) {
            throw GlobalException.build("用户信息不完整");
        }
        String token = (String) customer.get("token");
        String customerName = (String) customer.get("customerName");
        Integer payMode = mallService.getPayModeByOrgId(orgId);
        if (newIsVip != null && newIsVip == 0) {
            newIsVip = customerDao.getIsVip(customerId);
            newIsVip = newIsVip == null ? 0 : newIsVip;
        }
        WxUser wxUser = new WxUser(appUserId, null, appId, customerName, orgId,
                customerId, appUserId, payMode, isVip, bindPhone,
                (customer.containsKey("cover") && !StringUtils.isEmpty(customer.get("cover")) ? customer.get("cover").toString() : ""), "");

        String key = MD5.encode(orgId + appUserId);
        stringRedisTemplate.opsForValue().set("login:" + key, JSON.toJSONString(wxUser), 15, TimeUnit.MINUTES);
        String moduleUrl;
        String h5TokenParam = "?t=" + System.currentTimeMillis() + "&tk=" + appId + "&appUserId=" + oldAppUserId + "&appId=" + appId + "&ht=" + key;
        String scrmWebUrl = systemProperties.getAcsScrmWebUrl();
        if (WebModule.USER_CENTER.getModule().equals(m)) {
            moduleUrl = scrmWebUrl + Constants.URI_H5_USER_CENTER + h5TokenParam;
        } else if (WebModule.MALL.getModule().equals(m)) {
            moduleUrl = scrmWebUrl + Constants.URI_H5_MALL + h5TokenParam;
        } else {
            moduleUrl = m.replaceFirst("\\.html\\??", ".html" + h5TokenParam + "&");
        }
        return "redirect:" + moduleUrl;
    }

    /**
     * h5模块菜单管理
     */
    @Getter
    @AllArgsConstructor
    private enum WebModule {
        USER_CENTER("uc", "个人中心"), MALL("mall", "商城");
        private String module;
        private String info;
    }


    public int getChromeVersion(HttpServletRequest request, HttpServletResponse response) {
        String userAgent = request.getHeader("user-agent");
        Browser browser = UserAgent.parseUserAgentString(userAgent).getBrowser();
        if (browser != null && browser.getName().contains("Chrome")) {
            Version version = browser.getVersion(userAgent);
            if (!StringUtils.isEmpty(version.getMajorVersion())) {
                try {
                    int majorVersion = Integer.parseInt(version.getMajorVersion());
                    // 如果是谷歌并且版本小于等67，则samesite设置为null
                    LOGGER.info("=======当前谷歌版本为===========>" + majorVersion);
                    return majorVersion;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return 80;
    }

    public String appLoginThrid(String expandInfo, String appId, @RequestParam(defaultValue = "uc") String m, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(expandInfo) || StringUtils.isEmpty(appId)) {
            throw GlobalException.build("缺少参数");
        }
        Map<String, Object> customer = personalService.getAppCustomerByAppUserExpandInfo(expandInfo, appId);
        String customerId = (String) customer.get("customerId");
        String orgId = (String) customer.get("orgId");
        if (StringUtils.isEmpty(customerId) || StringUtils.isEmpty(orgId)) {
            throw GlobalException.build("用户信息不完整");
        }
        String token = (String) customer.get("token");
        String customerName = (String) customer.get("customerName");
        String appUserId = (String) customer.get("appUserId");
        Integer isVip = 0;
        if (!StringUtils.isEmpty(customer.get("isVip"))) {
            isVip = Integer.valueOf(customer.get("isVip").toString());
        }
        String bindPhone = customer.containsKey("bindPhone") && customer.get("bindPhone") != null ? customer.get("bindPhone").toString() : "";
        Integer payMode = mallService.getPayModeByOrgId(orgId);
        WxUser wxUser = new WxUser(appUserId, null, appId, customerName, orgId, customerId, appUserId, payMode,
                isVip, bindPhone,
                (customer.containsKey("cover") && !StringUtils.isEmpty(customer.get("cover")) ? customer.get("cover").toString() : ""), "");

        String key = MD5.encode(orgId + appUserId);
        //region 生成SH5TOKEN
        String h5User = stringRedisTemplate.opsForValue().get("login:" + key);
        if (!StringUtils.isEmpty(h5User)) {
            stringRedisTemplate.expire("login:" + key, 15, TimeUnit.MINUTES);
        } else {
            stringRedisTemplate.opsForValue().set("login:" + key, JSON.toJSONString(wxUser), 15, TimeUnit.MINUTES);
        }
        //endregion
        String oldAppUserId = null;
        try {
            oldAppUserId = AesEncryptUtils.encrypt(appUserId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String moduleUrl;
        String h5TokenParam = "?t=" + System.currentTimeMillis() + "&tk=" + token + "&isNav=1&appUserId=" + oldAppUserId + "&appId=" + appId + "&ht=" + key;
        String scrmWebUrl = systemProperties.getAcsScrmWebUrl();
        if (WebModule.USER_CENTER.getModule().equals(m)) {
            moduleUrl = scrmWebUrl + Constants.URI_H5_USER_CENTER + h5TokenParam;
        } else if (WebModule.MALL.getModule().equals(m)) {
            moduleUrl = scrmWebUrl + Constants.URI_H5_MALL + h5TokenParam;
        } else {
            moduleUrl = m.replaceFirst("\\.html\\??", ".html" + h5TokenParam + "&");
        }
        return "redirect:" + moduleUrl;
    }


    /**
     * @Description：雅智捷用户登录
     * @DateTime：2020/12/3 9:39
     * @Params：
     * @Return：
     */
    private String yzjLogin(String memberCode, String m, String token) {
        String orgId = personalService.getOrgByToken(token);
        LOGGER.info("yzjLogin---------memberCode:" + memberCode + "---------callback:" + m + "-----------token:" + token);
        Map<String, Object> customer = this.personalService.getCustomerInfoBySourceUserId(memberCode, orgId);
        Integer payMode = mallService.getPayModeByOrgId(orgId);
        if (customer != null) {
            Integer isVip = vipCustomerLogService.getIsVip(customer.get("customerId").toString(), customer.get("orgId").toString());
            WxUser wxUser = new WxUser((customer.containsKey("openId") && !StringUtils.isEmpty(customer.get("openId")) ? customer.get("openId").toString() : memberCode),
                    (customer.containsKey("payOpenId") && !StringUtils.isEmpty(customer.get("payOpenId")) ? customer.get("payOpenId").toString() : memberCode),
                    (customer.containsKey("token") && !StringUtils.isEmpty(customer.get("token")) ? customer.get("token").toString() : ""),
                    (customer.containsKey("customerName") && !StringUtils.isEmpty(customer.get("customerName")) ? customer.get("customerName").toString() : ""),
                    orgId,
                    customer.get("customerId").toString(),
                    (customer.containsKey("openId") && !StringUtils.isEmpty(customer.get("openId")) ? customer.get("openId").toString() : memberCode),
                    payMode,
                    isVip,
                    (customer.containsKey("bindPhone") && !StringUtils.isEmpty(customer.get("bindPhone")) ? customer.get("bindPhone").toString() : ""),
                    (customer.containsKey("cover") && !StringUtils.isEmpty(customer.get("cover")) ? customer.get("cover").toString() : ""),
                    memberCode);
            String key = MD5.encode(wxUser.getOrgId() + wxUser.getGlobalOpenid());
            stringRedisTemplate.opsForValue().set("login:" + key, JSON.toJSONString(wxUser), 15, TimeUnit.MINUTES);
            String url = this.getRedirectH5Url(wxUser, m, token,null);
            LOGGER.info("yzjLogin---------" + url);
            return "redirect:" + url;
        } else {
            Map<String, Object> customerInfo = this.yzjRequest.getMemberInfo(memberCode);
            if (customerInfo != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("customerName", customerInfo.get("full_name"));
                map.put("customerPhone", customerInfo.get("mobile"));
                map.put("customerEmail", customerInfo.get("email"));
                map.put("orgId", this.yzjRequest.yzjOrgId);
                map.put("customerCompany", null);
                map.put("customerFax", null);
                map.put("province", null);
                map.put("city", null);
                map.put("district", null);
                map.put("customerAddress", customerInfo.get("address"));
                map.put("source", 8);
                map.put("sourceMark", null);
                map.put("sourceUserId", customerInfo.get("member_code"));
                String customerId = this.syncService.third(map);
                WxUser wxUser = new WxUser("",
                        memberCode,
                        token,
                        (map.containsKey("customerName") && !StringUtils.isEmpty(map.get("customerName")) ? map.get("customerName").toString() : ""),
                        map.get("orgId").toString(),
                        customerId,
                        memberCode,
                        payMode,
                        0,
                        (map.containsKey("customerPhone") && !StringUtils.isEmpty(map.get("customerPhone")) ? map.get("customerPhone").toString() : ""),
                        "",
                        memberCode);
                String key = MD5.encode(wxUser.getOrgId() + wxUser.getGlobalOpenid());
                stringRedisTemplate.opsForValue().set("login:" + key, JSON.toJSONString(wxUser), 15, TimeUnit.MINUTES);
                String url = this.getRedirectH5Url(wxUser, m, token,null);
                LOGGER.info("yzjLogin-getzyjmemberinfo---------" + url);
                return "redirect:" + url;
            }
            throw GlobalException.build("未找到对应用户信息");
        }
    }
}

